from models.OpenAI import OpenAIClient
from models.MistralAI import MistralAI
from .Config import Config
import json

conversation_history = []


def create_client_and_chat(model_name, message: list):
    if model_name == "OPENAI":
        # 创建 OpenAI 客户端
        client = OpenAIClient(
            model_name=Config.model_name,
            model_path=Config.model_path,
            api_key=Config.api_key,
            top_p=Config.top_p,
            temperature=Config.temperature,
            max_tokens=Config.max_tokens
        )
    elif model_name == "MISTRALAI":
        # 创建 MistralAI 客户端
        client = MistralAI(
            model_name=Config.model_name,
            api_key=Config.api_key,
            top_p=Config.top_p,
            temperature=Config.temperature,
            max_tokens=Config.max_tokens
        )
    else:
        raise ValueError("Invalid model name. Please choose either 'OPENAI' or 'MISTRALAI'.")
    # 调用客户端的 chat 方法
    return client.chat(message)


def chat(message: list):
    default_models = Config.default_models
    # 调用 create_client_and_chat 函数，减少重复代码
    response = create_client_and_chat(default_models, message)
    return response


def request(message):
    """
    :param message:  用户返回信息
    :return:  {
                "description": "查看ip地址",
                "code": "ipconfig",
                "is_code": true,
                "Native": true
                }
    """
    conversation_history.append({"role": "user", "content": message})
    # 调用 chat 方法
    response = chat(conversation_history)
    # print(response)
    # 将 response 添加到对话历史中
    conversation_history.append({"role": "assistant", "content": response})

    # 解析 response 中的 ```json``` 部分
    try:
        # 首先判断有没有 ```json``` 部分
        if "```json" in response:
            start = response.find("```json")
            if start == -1:
                raise ValueError("No '```json' tag found in the response.")
            end = response.find("```", start + len("```json"))
            if end == -1:
                raise ValueError("No closing '```' tag found after '```json' in the response.")
            text = response[start + len("```json"):end].strip()

            # 解析 JSON 字符串为 Python 对象
            json_obj = json.loads(text)
            return json_obj
        elif "{" in response or "[" in response or "}" in response:
            json_obj = json.loads(response)
            return json_obj
    except ValueError as e:
        print(f"Error parsing JSON from response: {e}")
        return None


# 清空对话历史
def clear_history():
    conversation_history.clear()
